import store from '../repo/store/store'
import {LoginPathByType, LoginType} from '../repo/env/Constants'
import {push} from '../router/util'
import {authActionsTypes} from '../repo/store/auth'
import {delCookie} from 'as-common'
import {Dialog} from 'vant'
import cookies from '../repo/cookie/cookies'
import UserAPI from '../repo/api/UserAPI'
import {userActionsTypes, userTypes} from '../repo/store/user'

export function remoteLogin() {

  let loginType = store.state.auth.loginType;
  delCookie(LoginType.jumpAfterLogin,true)


  switch (loginType) {
    case LoginType.SIGN:
      signRemoteLogin()
      break;
    case LoginType.WX:
    case LoginType.MOBILE:
      store.dispatch(authActionsTypes.CLEAN_LOGGED_INFO, {})
        .then(_ => push(LoginPathByType[loginType]));
      break;
  }
}

export function loginOut() {
  let hsId = store.getters.hsId;
  let loginType = store.getters.loginType;
  setTimeout(() => {
    window.location.href = window.location.origin + `/web-hft-ee/myOrg/${loginType}/`+hsId;
  }, 500)

}


export function notToJoinTeam() {

  if (window.location.href.indexOf('notInvolved') > -1) {
    return
  }
  let hsId = store.getters.hsId;
  let loginType = store.getters.loginType;
  window.location.href = window.location.origin + `/web-hft-ee/notInvolved/${loginType}/` + hsId;

}

function signRemoteLogin() {
  Dialog({message: '链接已断开，请刷新', confirmButtonText: '刷新'}).then(() => {
    let sign = cookies.getSign()

    if (sign) {
      return store.dispatch(authActionsTypes.LOGIN_BY_SIGN, {sign})
        .then(() => {
          UserAPI.getUserInfo().then((result) => {
            store.commit(userTypes.SAVE_USER_INFO, result.responseData);
            store.dispatch(userActionsTypes.FETCH_ENTERPRISE_INFO).then(() => {
              window.location.reload();
            }).catch((e) => {
              this.$_router.push({name: 'auth-failed'})
            })
          }).catch((e) => {
            this.$_router.push({name: 'auth-failed'})
          })
        })



    }
    return store.dispatch(authActionsTypes.LOGOUT)
  })

}
